<template>
  <div class="quick-consultation">
    <div class="header">
      <span class="back-icon">&lt;</span>
      <span class="title">快速问诊</span>
      <span class="notification">🔔</span>
    </div>
    <div style="border: 1px solid #0f0f0f;">
      <div style="width:300px;font-size: 16px;display: inline-block;padding: 0px 10px;">
        <div><span>当前状态：{{ this.state ? "你已连接上服务端" : "未连接" }}</span></div>
        <div style="margin-top: 10px">
          <div><span>好友昵称：</span></div>
          <input placeholder="请输入好友昵称" style="width:100%;" v-model="target" />
          <!-- <button @click="connection()" style="width:100%;margin-top: 10px;">加入聊天</button> -->
        </div>
        <div style="margin-top:10px">
          <div><span>昵称(必填)：</span></div>
          <input placeholder="行不更名坐不改姓，江湖人称?" v-model="name" style="width:100%" />
        </div>
        <div style="margin-top:10px">
          <div><span>WebSocket地址(必填)：</span></div>
          <input placeholder="WS地址" style="width:100%;" v-model="wsAddress" />
          <button @click="connectWebsocket()" style="width:100%;margin-top: 10px;">上线</button>
        </div>
        <div style="margin-top:10px">
          <button @click="this.messageList = []" style="width:100%;">清屏</button>
        </div>

        <div style="margin-top:10px">
          <button @click="downLine()" style="width:100%;">下线</button>
        </div>
        <!-- <div style="margin-top:10px">
            <button @click="joinGroup()" style="width:100%;">加入系统群聊</button>
        </div> -->
        <div style="margin-top:10px">
          <button @click="clearAllOnlineUsers()" style="width:100%;background-color: #ff4d4f;color: white;">清空所有在线用户</button>
        </div>
      </div>
      <div class="message_group">
        <div style="margin-bottom: 10px;" v-for="(item, index) in messageList" :key="index">
          <div style="color:blueviolet;font-weight: bold;" :style="{ 'color': item.self ? '#2aae67' : '#666' }">{{
              item.self ?  name +'医生' : '' +
                item.name
            }} <span>{{ item.time }}</span></div>
          <div :class="['message-content', {'prescription-card': item.isPrescription}]"
               style="color: #666" @click="handlePrescriptionClick(item)"
               :style="{ cursor: item.isPrescription ? 'pointer' : 'default' }">
            {{ item.message }}
          </div>
        </div>
      </div>
      <div class="sendMessages">
        <input placeholder="请输入发送内容" class="input-area" v-model="content" />
        <button class="send-btn" @click="sendMessage(1)">发送</button>
        <!-- ★★★ 开处方按钮 ★★★ -->
        <div class="tool-item prescription" @click="openPrescription">
          开处方
        </div>
        <button class="video-call-btn" @click="startVideoCall">
          <img src="@/assets/images/屏幕截图 2025-03-08 115150.png" alt="视频通话" width="24" height="24"/>
        </button>
      </div>
      <div v-if="currentDoctor" class="video-call" @click="startVideoCall">
        <img src="@/assets/images/屏幕截图 2025-03-08 115150.png" alt="视频通话" width="24" height="24"/>
      </div>

    </div>

    <!-- 添加视频通话处理的消息监听 -->
    <div v-if="showVideoCall" class="video-call-dialog">
      <div class="video-call-content">
        <h3>视频通话请求</h3>
        <p>收到来自患者的视频通话请求</p>
        <div class="video-call-actions">
          <button class="accept-btn" @click="acceptVideoCall">接受</button>
          <button class="reject-btn" @click="rejectVideoCall">拒绝</button>
        </div>
      </div>
    </div>

    <!-- 添加处方详情弹窗 -->
    <el-dialog
      title="处方详情"
      :visible.sync="showPrescriptionDetail"
      width="50%">
      <div v-if="prescriptionDetail" class="prescription-detail">
        <div class="detail-item">
          <span class="label">患者姓名：</span>
          <span>{{ prescriptionDetail.patientName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">年龄：</span>
          <span>{{ prescriptionDetail.age }}</span>
        </div>
        <div class="detail-item">
          <span class="label">性别：</span>
          <span>{{ prescriptionDetail.sex }}</span>
        </div>
        <div class="detail-item">
          <span class="label">诊断结果：</span>
          <span>{{ prescriptionDetail.diagnosis }}</span>
        </div>
        <div class="detail-item">
          <span class="label">开具药品：</span>
          <div class="drug-list">
            <div v-for="(drug, index) in prescriptionDetail.drugNames" :key="index" class="drug-item">
              {{ drug }}
            </div>
          </div>
        </div>
      </div>
    </el-dialog>




<!--    -->
    <el-dialog :visible.sync="kaichufang" >
      <div class="chat-container">
        <!-- 顶部导航 -->
        <div class="nav-header">
          <i class="el-icon-arrow-left"></i>
          <div class="title">我的药房</div>
          <div class="notification-icon">🔔</div>
        </div>
        <!--    按钮-->
        <div class="nav-headers">
          <div class="titles" @click="commonlyUsedDrugs()">常用药品</div>
          <div class="titles" @click="commonPrescription1()">常用处方</div>
          <div class="titles" @click="historicalPrescription()">历史处方</div>
        </div>

        <!--    常用药品-->
        <div v-if="myPharmacy == 1">
          <template>
            <el-table :data="tableData" style="width: 100%">
              <el-table-column width="180">
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{ scope.row.restorativesId }}</span>
                </template>
              </el-table-column>
              <el-table-column width="180">
                <template slot-scope="scope">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="scope.row.picture"></el-image>
                </template>
              </el-table-column>
              <el-table-column width="180">
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{ scope.row.drugName }}</span>
                </template>
              </el-table-column>
              <el-table-column width="180">
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{ scope.row.price }}元</span>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>

        <!--    常用处方-->
        <div v-if="myPharmacy == 2">
          <div class="card-list">
            <el-button @click="newPrescription()">新建处方</el-button>
            <div v-for="item in cardList" :key="item.patientId" class="card-item" @click="commonPrescription(item.prescriptionId)">
              <!-- 卡片左侧 -->
              <div class="card-left">
                <div class="card-desc">临床诊断: {{ item.diagnosis }}</div>
              </div>
            </div>
          </div>
        </div>

        <!--    历史处方-->
        <div v-if="myPharmacy == 3">
          <div class="card-list">
            <div v-for="item in cardList2" :key="item.patientId" class="card-item" @click="HistoricalPrescription(item.id)">
              <!-- 卡片左侧 -->
              <div class="card-left">
                <div class="card-info">
                  <span class="info-item">{{ item.name }}</span>
                  <span class="info-item">{{ item.sex }}</span>
                  <span class="info-item">{{ item.age }}</span>
                </div>
                <div class="card-desc">临床诊断: {{ item.diagnosis }}</div>
              </div>
            </div>
          </div>
        </div>

        <!--    常用药品详情-->
        <el-dialog title="常用药品详情" :visible.sync="dialogVisibleCommonlyUsedDrugs">
          <el-form label-width="80px" :model="formLabelAlignCommonlyUsedDrugs">
            <el-form-item label="图片">
              {{formLabelAlignCommonlyUsedDrugs.picture}}
            </el-form-item>
            <el-form-item label="药品名称">
              {{formLabelAlignCommonlyUsedDrugs.drugName}}
            </el-form-item>
            <el-form-item label="价格">
              {{formLabelAlignCommonlyUsedDrugs.price}}
            </el-form-item>
            <el-form-item label="药品说明:">
              {{formLabelAlignCommonlyUsedDrugs.drugDescription}}
            </el-form-item>
          </el-form>
          <el-button @click="dialogVisibleCommonlyUsedDrugs = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisibleCommonlyUsedDrugs = false">确 定</el-button>
        </el-dialog>
        <!--    常用处方详情-->
        <el-dialog title="常用处方详情" :visible.sync="dialogVisibleCommonPrescription">
          <el-form label-width="80px" :model="formLabelAlignCommonPrescription">
            <el-form-item label="诊断">
              {{formLabelAlignCommonPrescription.diagnosis}}
            </el-form-item>
            <el-form-item label="药品">
              {{formLabelAlignCommonPrescription.drugName}}
            </el-form-item>
          </el-form>
          <el-button @click="dialogVisibleCommonPrescription = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisibleCommonPrescription = false">确 定</el-button>
        </el-dialog>
        <!--    历史处方详情-->
        <el-dialog title="历史处方详情" :visible.sync="dialogVisibleHistoricalPrescription">
          <el-form label-width="80px" :model="formLabelAlignHistoricalPrescription">
            <el-form-item label="患者姓名">
              {{formLabelAlignHistoricalPrescription.name}}
            </el-form-item>
            <el-form-item label="患者年龄">
              {{formLabelAlignHistoricalPrescription.sex}}
            </el-form-item>
            <el-form-item label="患者性别">
              {{formLabelAlignHistoricalPrescription.age}}
            </el-form-item>
            <el-form-item label="诊断名称:">
              {{formLabelAlignHistoricalPrescription.diagnosis}}
            </el-form-item>
            <el-form-item label="药品名称">
              {{formLabelAlignHistoricalPrescription.drugNames}}
            </el-form-item>
          </el-form>
          <el-button @click="dialogVisibleHistoricalPrescription = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisibleHistoricalPrescription = false">确 定</el-button>
        </el-dialog>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="addchufang">
      <div class="chat-container">
        <!--    处方信息-->
        <el-form label-width="80px" :model="formLabelAlign">
          <el-form-item label="患者id" class="hidden-label">
            <el-input v-model="formLabelAlign.patientId"></el-input>
          </el-form-item>
          <el-form-item label="患者姓名">
            <el-input v-model="formLabelAlign.name"></el-input>
          </el-form-item>
          <el-form-item label="患者年龄">
            <el-input v-model="formLabelAlign.age"></el-input>
          </el-form-item>
          <el-form-item label="患者性别">
            <el-input v-model="formLabelAlign.sex"></el-input>
          </el-form-item>
          <el-form-item label="诊断id" class="hidden-label">
            <el-input v-model="formLabelAlign.prescriptionId"></el-input>
          </el-form-item>
          <el-form-item label="诊断名称">
            <el-input v-model="formLabelAlign.diagnosis"></el-input>
            <el-button @click="diagnosticListButton()">诊断列表</el-button>
          </el-form-item>
          <el-form-item label="药品id" class="hidden-label">
            <el-input v-model="formLabelAlign.restorativesIds.join(',')" readonly></el-input>
          </el-form-item>
          <el-form-item label="药品名称">
            <el-input v-model="formLabelAlign.drugNamesDisplay" readonly></el-input>
            <el-button @click="drugListButton()">药品列表</el-button>
          </el-form-item>
        </el-form>

        <!--    药品对话框-->
        <el-dialog title="药品列表" :visible.sync="dialogVisible" >
          <el-table :data="tableData" style="width: 100%">
            <el-table-column label="药品id" width="180">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.restorativesId }}</span>
              </template>
            </el-table-column>
            <el-table-column label="药品名称" width="180">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.drugName }}</span>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot-scope="scope">
                <el-button @click="handleClick(scope.row)" type="text" size="small">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </el-dialog>

        <!--      症状列表对话框-->
        <el-dialog title="症状列表" :visible.sync="symptomList" >
          <el-table :data="tableData2" style="width: 100%">
            <el-table-column label="药品id" width="180">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.prescriptionId }}</span>
              </template>
            </el-table-column>
            <el-table-column label="药品名称" width="180">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.diagnosis }}</span>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot-scope="scope">
                <el-button @click="handleClick2(scope.row)" type="text" size="small">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button @click="symptomList = false">取 消</el-button>
          <el-button type="primary" @click="symptomList = false">确 定</el-button>
        </el-dialog>

        <el-button @click="sendAPrescription()">发送处方</el-button>
        <el-button @click="sendAPrescription2()">发送处方(测试)</el-button>

      </div>
    </el-dialog>
  </div>
</template>
<script>
import md5 from 'js-md5'
import {
  historicalPrescriptionDetails,
  listOfHistoricalPrescriptions
} from '@/api/doctorTerminal/myPharmacy/historicalPrescription'
import {detailsOfCommonDrugs} from "@/api/doctorTerminal/myPharmacy/writeAPrescription";
import {commonPrescription} from "@/api/doctorTerminal/myPharmacy/commonPrescription";
import {listOfCommonDrugs} from "@/api/doctorTerminal/myPharmacy/commonlyUsedDrugs";
import {makeAPrescriptionAdd, queryPatientInformationById, seeYourDoctorForSymptoms} from "@/api/doctorTerminal/myPharmacy/writeAPrescription";
export default {
  data() {
    return {
      // 常用药品详情对象
      formLabelAlignCommonlyUsedDrugs: {
        // 图片
        picture:'',
        // 药品名称
        drugName:'',
        // 价格
        price:'',
        // 药品说明
        drugDescription:'',
      },
      // 常用处方详情对象
      formLabelAlignCommonPrescription: {
        // 诊断
        diagnosis:'',
        // 药品
        drugName:'',
      },
      // 历史处方详情对象
      formLabelAlignHistoricalPrescription: {
        name: '',
        sex: '',
        age: 0,
        diagnosis: '',
        drugNames: '',
      },

      // 常用药品对话框
      dialogVisibleCommonlyUsedDrugs: false,
      kaichufang: false,
      addchufang: false,
      // 常用处方对话框
      dialogVisibleCommonPrescription: false,
      // 历史处方对话框
      dialogVisibleHistoricalPrescription: false,
      // 列表
      tableData: [],
      // 变量
      myPharmacy: 1,
      // userId
      doctorId: this.$store.state.user.id,
      // 常用处方列表
      cardList: [],
      // 历史处方列表
      cardList2: [],
      // 从问诊跳转的id
      id: 0,
      inner_ip: '',
      target: '',
      name: '',
      messageList: [],
      wsAddress: 'ws://localhost:1212',
      websocket: null,
      content: '',
      state: false,
      showVideoCall: false,
      pendingVideoCall: null,
      currentDoctor: null,
      showVideoCallButton: true,
      showPrescriptionDetail: false,
      prescriptionDetail: null,
      prescriptionId: null,
      // 症状列表对话框
      symptomList: false,
      // 药品列表对话框
      dialogVisible: false,
      // 开处方对象
      formLabelAlign: {
        id: '',
        patientId: '',
        name: '',
        age: '',
        sex: '',
        prescriptionId: '',
        diagnosis: '',
        restorativesIds: [],
        drugNames: [],
        doctorId: this.$store.state.user.id
      },
      // 症状列表
      tableData2: [],
    }
  },
  mounted() {

    const { id, name, ids, diagnosis, drugName } = this.$route.query;

    if(id && name){
      // 医生端初始化
      this.target = "患者";
      this.name = "admin";  // 修改为 admin
    } else {
      // 患者端初始化
      this.name = "患者";
      this.target = "admin";
    }

    // 只保留获取内网 IP
    this.getUserIP((rs) => {
      console.log(rs)
      this.inner_ip = rs;
    });

    // 添加页面关闭事件监听
    window.addEventListener('beforeunload', (event) => {
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        event.preventDefault();
        this.downLine();
        event.returnValue = '';
      }
    });

    // 如果有处方信息，添加到消息列表中
    if (ids && diagnosis && drugName) {
      this.messageList.push({
        name: '系统消息',
        message: this.createPrescriptionCard(diagnosis, drugName),
        time: new Date().toLocaleString(),
        self: true,
        isPrescription: true  // 标记这是一个处方消息
      });
    }
  },
  created() {
    this.getDataDrug()
    this.getDataCommonPrescription()
    this.aa()
    this.getPatient()
  },
  methods: {
    // 药品列表
    getData() {
      listOfCommonDrugs(this.doctorId).then(res =>{
        console.log("药品列表: " , res)
        this.tableData = res
      })
    },
    // 症状列表
    getSymptom() {
      seeYourDoctorForSymptoms(this.doctorId).then(res =>{
        console.log("症状列表: " , res)
        this.tableData2 = res
      })
    },
    // 患者信息
    getPatient() {
      queryPatientInformationById(1).then(res =>{
        console.log("患者信息: " , res)
        this.formLabelAlign.patientId = res.patientInformationId
        this.formLabelAlign.name = res.name
        this.formLabelAlign.age = res.age
        this.formLabelAlign.sex = res.sex
      })
    },
    /** 添加药品 **/
    handleClick(row) {
      // 确保是数组
      if (!this.formLabelAlign.restorativesIds) {
        this.formLabelAlign.restorativesIds = [];
      }
      if (!this.formLabelAlign.drugNames) {
        this.formLabelAlign.drugNames = [];
      }

      // 添加新选择的药品
      this.formLabelAlign.restorativesIds.push(row.restorativesId);
      this.formLabelAlign.drugNames.push(row.drugName);

      // 更新显示的药品名称（转为字符串）
      const drugNamesStr = this.formLabelAlign.drugNames.join('、');
      this.$set(this.formLabelAlign, 'drugNamesDisplay', drugNamesStr);
    },
    /** 添加症状 */
    handleClick2(row) {
      this.formLabelAlign.prescriptionId = row.prescriptionId
      this.formLabelAlign.diagnosis = row.diagnosis
    },
    // 诊断列表按钮
    diagnosticListButton() {
      this.getSymptom()
      this.symptomList = true;
    },
    // 药品列表按钮
    drugListButton() {
      this.getData()
      this. dialogVisible = true;
    },
    // 发送处方
    sendAPrescription() {
      makeAPrescriptionAdd(this.formLabelAlign).then(res => {
        console.log("发送处方后返回的数据: ", res.data)
        localStorage.setItem('savePrescriptionId',res.data.id);
        if (res.code === 200 || res.code === 0) {
          // 构造处方消息
          const prescriptionMessage = {
            code: "10002",
            type: 1,
            nickname: "医生",
            target: "患者",
            messageType: "prescription",
            content: `处方信息：\n诊断结果：${this.formLabelAlign.diagnosis}\n开具药品：${Array.isArray(this.formLabelAlign.drugNames) ? this.formLabelAlign.drugNames.join('、') : this.formLabelAlign.drugNames}\n【点击查看详情】`,
            prescriptionData: {
              patientName: this.formLabelAlign.name,
              age: this.formLabelAlign.age,
              sex: this.formLabelAlign.sex,
              diagnosis: this.formLabelAlign.diagnosis,
              drugNames: Array.isArray(this.formLabelAlign.drugNames) ? this.formLabelAlign.drugNames : [this.formLabelAlign.drugNames]
            }
          };

          console.log('医生端准备发送处方消息：', prescriptionMessage);

          if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
            this.websocket.send(JSON.stringify(prescriptionMessage));

            // 添加到本地消息列表
            this.messageList.push({
              name: "医生",
              message: prescriptionMessage.content,
              messageType: "prescription",
              time: new Date().toLocaleString(),
              self: true,
              isPrescription: true,
              prescriptionData: prescriptionMessage.prescriptionData
            });

            console.log('处方消息已发送');
            this.$message.success('处方发送成功');
            // 关闭新建处方弹窗
            this.addchufang = false;
            // 关闭我的药房弹窗
            this.kaichufang = false;
          }
        }
      });
    },
    // 测试
    sendAPrescription2() {
      // 创建测试处方数据
      const testPrescription = {
        id: 9,
        diagnosis: "脑血管病",
        drugName: "999皮炎领1"
      };

      // 将测试处方添加到消息列表
      this.messageList.push({
        name: '系统消息',
        message: this.createPrescriptionCard(testPrescription.diagnosis, testPrescription.drugName),
        time: new Date().toLocaleString(),
        self: true,
        isPrescription: true
      });

      // 关闭处方弹窗
      this.addchufang = false;

      // 提示成功
      this.$message.success('测试处方发送成功');
    },
    // 判断是否是跳转过来的
    aa() {
      if (this.$route.query.id)
      {
        this.myPharmacy = 2
        console.log("this.myPharmacy: ", this.myPharmacy)
      }
    },
    // B端 我的药房 常用药列表
    getDataDrug() {
      listOfCommonDrugs(this.doctorId).then(res =>{
        console.log("B端 我的药房 常用药列表: ", res)
        this.tableData = res
      })
    },
    // B端 我的药房 常用处方列表
    getDataCommonPrescription() {
      commonPrescription(this.doctorId).then(res => {
        console.log("B端 我的药房 常用处方列表: ", res)
        this.cardList = res
      })
    },
    // B端 我的药房 历史处方列表
    getDataListOfHistoricalPrescriptions() {
      listOfHistoricalPrescriptions(this.doctorId).then(res => {
        console.log("B端 我的药房 历史处方列表: ", res)
        this.cardList2 = res
      })
    },
    // 常用药品
    commonlyUsedDrugs()
    {
      this.myPharmacy = 1;
    },

    // 常用处方
    commonPrescription1()
    {
      this.myPharmacy = 2;
    },

    // 历史处方
    historicalPrescription()
    {
      this.myPharmacy = 3;
      this.getDataListOfHistoricalPrescriptions()
    },

    // 新建处方
    newPrescription() {
      this.addchufang=true
    },
    // 常用药品详情对象
    handleEdit($index, row) {
      alert("常用药品详情对象: " + row.restorativesId)
      detailsOfCommonDrugs().then(res =>{

      })
    },
    // 常用处方详情对象
    commonPrescription(patientId) {
      alert("常用处方详情对象: " + patientId)
    },
    // 历史处方详情对象
    HistoricalPrescription(id) {
      alert("历史处方详情对象: " + id)
    },


    // ★★★ 打开处方页面 ★★★
    openPrescription() {
      // 如果有患者信息，自动填充
      if (this.$route.query.id) {
        queryPatientInformationById(this.$route.query.id).then(res => {
          if (res.code === 0 && res.data) {
            this.formLabelAlign.patientId = res.data.patientInformationId;
            this.formLabelAlign.name = res.data.name;
            this.formLabelAlign.age = res.data.age;
            this.formLabelAlign.sex = res.data.sex;
          }
        }).catch(error => {
          console.error('获取患者信息失败:', error);
        });
      }

      // 打开处方弹窗
      this.kaichufang = true;
    },
    generateID() {
      // 使用时间戳和随机数生成唯一ID
      return md5(Date.now() + this.generateMixed(18));
    },
    connection() {
      // if (this.target === null || this.target === '') {
      //     alert('链接地址不能为空')
      // }
      // if (this.target === this.name) {
      //     alert('你自己和你聊天？')
      // }
    },
    // 获取当前网络ip
    getUserIP(onNewIP) {
      const MyPeerConnection =
        window.RTCPeerConnection ||
        window.mozRTCPeerConnection ||
        window.webkitRTCPeerConnection

      const pc = new MyPeerConnection({
        iceServers: []
      })
      const noop = () => { }
      const localIPs = {}
      const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g
      const iterateIP = (ip) => {
        if (!localIPs[ip]) onNewIP(ip)
        localIPs[ip] = true
      }

      pc.createDataChannel('')

      pc.createOffer()
        .then((sdp) => {
          sdp.sdp.split('\n').forEach(function (line) {
            if (line.indexOf('candidate') < 0) return

            line.match(ipRegex).forEach(iterateIP)
          })

          pc.setLocalDescription(sdp, noop, noop)
        })
        .catch((reason) => { })
      pc.onicecandidate = (ice) => {
        if (
          !ice ||
          !ice.candidate ||
          !ice.candidate.candidate ||
          !ice.candidate.candidate.match(ipRegex)
        ) { return }

        ice.candidate.candidate.match(ipRegex).forEach(iterateIP)
      }
    },
    joinGroup() {
      this.websocket.send(JSON.stringify({
        "code": "10003",
        "nickname": this.name,
      }))
    },
    sendMessage(type) {
      if (this.websocket === null || !this.websocket.readyState === 1) {
        this.$message.error("请先连接至服务端");
        return;
      }
      if (!this.content.trim()) {
        this.$message.error("消息内容不能为空");
        return;
      }

      // 只发送一次消息
      const messageData = {
        "code": "10002",
        "nickname": this.name,  // 固定使用 admin
        "content": this.content,
        "target": "患者",    // 固定发送给患者
        "type": type
      };

      console.log("医生发送消息：", messageData);
      this.websocket.send(JSON.stringify(messageData));

      // 添加到本地消息列表
      this.messageList.push({
        "name": '私聊消息(医生)',
        "message": this.content,
        "time": new Date().toLocaleString(),
        "self": true
      });

      this.content = '';
    },

    connectWebsocket() {
      // 先关闭已存在的连接
      if (this.websocket) {
        this.websocket.close();
        this.websocket = null;
      }

      if (this.name === null || this.name === '') {
        alert("请设置昵称再进互联网~")
        return
      }

      try {
        this.websocket = new WebSocket(this.wsAddress);

        this.websocket.onopen = (evt) => {
          this.state = this.websocket.readyState === 1;
          // 发送上线消息
          this.websocket.send(JSON.stringify({
            "code": "10001",
            "nickname": this.name
          }));
          // 加入群组
          setTimeout(() => {
            this.joinGroup();
          }, 500);
        }

        // 统一的消息处理逻辑
        this.websocket.onmessage = evt => {
          try {
            const data = JSON.parse(evt.data);
            console.log("医生收到消息：", data);

            // 检查是否是视频通话请求（通过消息内容判断）
            if (data.message && data.message.startsWith('2-')) {
              // 显示视频通话弹窗
              this.showVideoCall = true;
              this.pendingVideoCall = {
                roomId: data.message,
                from: '患者'
              };

              // 添加到消息列表
              this.messageList.push({
                "name": "系统消息",
                "message": `收到来自患者的视频通话请求`,
                "time": new Date().toLocaleString(),
                "self": false
              });
              return;
            }

            // 处理其他消息
            this.messageList.push({
              "name": data.name || "系统消息",
              "message": data.message || data.content,
              "time": data.time || new Date().toLocaleString(),
              "self": false
            });
          } catch (error) {
            console.error('处理消息时出错：', error);
          }
        };

        this.websocket.onerror = evt => {
          console.log("websocket错误：", evt);
          this.state = false;
        };

        this.websocket.onclose = evt => {
          console.log("websocket关闭：", evt);
          this.state = false;
          this.websocket = null;

          // 添加关闭提示
          this.messageList.push({
            "name": "系统消息",
            "message": "连接已断开",
            "time": new Date().toLocaleString(),
            "self": false
          });
        };
      } catch (error) {
        console.error("WebSocket 连接失败：", error);
        this.state = false;
      }
    },

    // 添加聊天记录方法
    async recording(chatData) {
      try {
        const recordData = {
          content: chatData.content || this.messageList.map(msg => ({
            type: msg.self ? 'doctor' : 'patient',
            content: msg.message,
            time: msg.time
          })),
          doctorPersonal: chatData.doctorPersonal || [{
            doctorName: this.name,
            // 其他医生相关信息
          }]
        };
      } catch (error) {
        console.error('记录聊天历史失败：', error);
      }
    },

    // 修改 downLine 方法，添加记录功能
    async downLine() {
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        try {
          // 记录聊天历史
          await this.recording({
            content: this.messageList,
            doctorPersonal: [{
              doctorName: this.name,
              // 其他医生信息
            }]
          });

          // 发送下线消息前先退出群组
          this.websocket.send(JSON.stringify({
            "code": "10003",
            "nickname": this.name,
            "type": "exit"  // 添加退出标识
          }));

          // 等待一小段时间后发送下线消息
          setTimeout(() => {
            // 发送下线消息
            this.websocket.send(JSON.stringify({
              "code": "10004",
              "nickname": this.name,
              "target": this.target,
              "type": "offline"  // 添加下线标识
            }));

            // 添加下线提示到消息列表
            this.messageList.push({
              "name": "系统消息",
              "message": `${this.name}已下线`,
              "time": new Date().toLocaleString(),
              "self": false
            });

            // 关闭连接前确保消息发送完成
            setTimeout(() => {
              if (this.websocket) {
                this.websocket.close();
                this.websocket = null;
                this.state = false;
              }
            }, 500);
          }, 500);
        } catch (error) {
          console.error("下线失败：", error);
          // 强制关闭连接
          if (this.websocket) {
            this.websocket.close();
            this.websocket = null;
            this.state = false;
          }
        }
      } else {
        // 如果连接已经关闭，直接清理状态
        this.websocket = null;
        this.state = false;
      }
    },
    generateMixed(n) {
      var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
      var res = "";
      for (var i = 0; i < n; i++) {
        var id = Math.floor(Math.random() * 36);
        res += chars[id];
      }
      return res;
    },
    // 添加一个新方法来清空所有在线用户
    clearAllOnlineUsers() {
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        // 发送清空在线用户的消息
        this.websocket.send(JSON.stringify({
          "code": "10005",  // 新的消息类型，用于清空在线用户
          "nickname": this.name,
          "type": "clear_all"
        }));

        // 关闭所有连接
        this.websocket.close();
        this.websocket = null;
        this.state = false;

        // 添加系统消息
        this.messageList.push({
          "name": "系统消息",
          "message": "已清空所有在线用户",
          "time": new Date().toLocaleString(),
          "self": false
        });
      }
    },
    // 接受视频通话
    acceptVideoCall() {
      if (!this.pendingVideoCall) return;

      // 构建视频通话 URL，使用相对路径
      const url = `/toMeeting?userId=医生&roomId=${this.pendingVideoCall.roomId}`;

      // 构建完整的 HTTPS URL
      const protocol = 'https:';
      const host = window.location.hostname;
      const port = '8087';
      const fullUrl = `${protocol}//${host}:${port}${url}`;

      // 添加证书信任选项
      const windowFeatures = 'width=800,height=600,menubar=no,toolbar=no,location=no,status=no';
      window.open(fullUrl, '_blank', windowFeatures);

      this.showVideoCall = false;
      this.pendingVideoCall = null;
    },
    // 拒绝视频通话
    rejectVideoCall() {
      if (!this.pendingVideoCall) return;

      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(JSON.stringify({
          code: 10002,    // 改为数字类型
          type: 1,        // 改为数字类型
          nickname: "医生",
          target: "患者",
          content: "医生拒绝了视频通话",
          messageType: "video_call_reject"  // 添加消息类型标识
        }));
      }

      this.showVideoCall = false;
      this.pendingVideoCall = null;
    },
    // 医生发起视频通话
    startVideoCall() {
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        try {
          const roomId = `2-${Date.now()}`;

          // 发送视频通话请求给患者
          this.websocket.send(JSON.stringify({
            code: 10002,
            type: 1,
            nickname: "医生",
            target: "患者",
            content: roomId,
            messageType: "video_call"
          }));

          // 直接打开视频通话窗口
          const protocol = 'https:';
          const host = window.location.hostname;
          const port = '8087';
          const url = `/toMeeting?userId=医生&roomId=${roomId}`;
          const fullUrl = `${protocol}//${host}:${port}${url}`;

          // 打开视频通话窗口
          const windowFeatures = 'width=800,height=600,menubar=no,toolbar=no,location=no,status=no';
          window.open(fullUrl, '_blank', windowFeatures);

          // 添加到消息列表
          this.messageList.push({
            "name": "系统消息",
            "message": "已发起视频通话",
            "time": new Date().toLocaleString(),
            "self": true
          });
        } catch (error) {
          console.error('发起视频通话失败:', error);
          this.$message.error('发起视频通话失败，请重试');
        }
      } else {
        this.$message.error('请先连接服务器');
      }
    },
    // 修改创建处方卡片的方法
    createPrescriptionCard(diagnosis, drugName) {
      // 确保药品名称是数组形式
      const drugNames = Array.isArray(drugName) ? drugName : [drugName];

      return `处方信息：
诊断结果：${diagnosis}
开具药品：${drugNames.join('、')}
【点击查看详情】`;  // 添加点击查看详情的提示
    },
    // 修改处方详情弹窗的处理
    async handlePrescriptionClick(item) {
      if (!item.isPrescription) return;  // 如果不是处方消息，直接返回

      try {
        // 使用发送处方时保存的数据直接显示
        this.prescriptionDetail = {
          patientName: this.formLabelAlign.name || '未知',
          age: this.formLabelAlign.age || '未知',
          sex: this.formLabelAlign.sex || '未知',
          diagnosis: item.message.split('诊断结果：')[1].split('\n')[0],  // 从消息中提取诊断
          drugNames: item.message.split('开具药品：')[1].split('\n')[0].split('、')  // 从消息中提取药品
        };

        // 如果有处方ID，尝试从服务器获取最新数据
        if (item.prescriptionId) {

          const response = await historicalPrescriptionDetails(item.prescriptionId);
          if (response.code === 0 || response.code === 200) {
            this.prescriptionDetail = {
              patientName: response.data.name,
              age: response.data.age,
              sex: response.data.sex,
              diagnosis: response.data.diagnosis,
              drugNames: Array.isArray(response.data.drugName)
                ? response.data.drugName
                : [response.data.drugName]
            };
          }
        }

        // 显示处方详情弹窗
        this.showPrescriptionDetail = true;
      } catch (error) {
        console.error('获取处方详情失败：', error);
        this.$message.error('获取处方详情失败');
      }
    },
  },
  beforeRouteLeave(to, from, next) {
    if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
      this.downLine();
    }
    next();
  },
  beforeDestroy() {
    if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
      this.downLine();
    }
  },
  destroyed() {
    window.removeEventListener('beforeunload', this.downLine);
  }
}
</script>
<style scoped>
.message_group {
  width: calc(100% - 600px);
  height: 400px;
  display: inline-block;
  padding: 10px;
  overflow-y: scroll;
  vertical-align: top;
  border-left: 1px solid #0f0f0f;
}
.sendMessages{
  margin-left: 300px;
  width: calc(100% - 600px);
  height: 400px;
  display: inline-block;
  padding: 10px;
  vertical-align: top;
  border-left: 1px solid #0f0f0f;
}
.quick-consultation {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background-color: #4080ff;
  color: white;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
}



.avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.message-bubble {
  background-color: white;
  padding: 10px 15px;
  border-radius: 10px;
  max-width: 80%;
}

.quick-select {
  padding: 15px;
}

.hint-text {
  color: #666;
  margin-bottom: 10px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-btn {
  background-color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 20px;
  color: #4080ff;
  font-size: 14px;
}
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}
.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #4169E1;
  color: white;
}
.nav-headers {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: white;
  color: #000000;
}


.card-left {
  flex: 1;
  margin-right: 40px; /* 增加左右内容间距 */
}
.card-item {
  background: #ffffff;
  border-radius: 12px; /* 增加圆角 */
  padding: 24px 32px; /* 增加内部间距 */
  display: flex;
  justify-content: space-between;
  align-items: flex-start; /* 改为顶部对齐 */
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  min-height: 160px; /* 设置最小高度 */
}
.card-list {
  display: flex;
  flex-direction: column;
  gap: 24px; /* 增加卡片之间的间距 */
  max-width: 1200px; /* 增加最大宽度 */
  margin: 0 auto;
}
.card-desc {
  font-size: 16px; /* 增加描述文字字号 */
  color: #666;
  line-height: 1.6;
  min-height: 48px; /* 设置最小高度确保对齐 */
}
.card-info {
  display: flex;
  gap: 24px; /* 增加信息项间距 */
  margin-bottom: 20px; /* 增加描述下方间距 */
}
.info-item {
  font-size: 14px; /* 增加信息项字号 */
  color: #999;
  display: flex;
  align-items: center;
}
.input-area {
  bottom: 0;
  width: 60%;
  background-color: white;
  padding: 8px;
}

.input-hint {
  color: #999;
  font-size: 12px;
  margin-bottom: 10px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  background: none;
  border: none;
  color: #666;
  font-size: 14px;
}

.send-btn {
  margin-left: 10px;
  background-color: #4080ff;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 5px;
}

.video-call-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 9999;
  min-width: 300px;
  border: 2px solid #4a90e2;
}

.video-call-content {
  text-align: center;
}

.video-call-content h3 {
  margin-bottom: 10px;
  color: #333;
}

.video-call-content p {
  margin-bottom: 20px;
  color: #666;
}

.video-call-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.accept-btn {
  padding: 8px 24px;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.reject-btn {
  padding: 8px 24px;
  background-color: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.accept-btn:hover {
  background-color: #357abd;
}

.reject-btn:hover {
  background-color: #e8e8e8;
}

.video-call-btn {
  margin-left: 10px;
  background-color: #4080ff;
  color: white;
  border: none;
  padding: 8px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-call-btn:hover {
  background-color: #357abd;
}

.video-call-btn img {
  width: 24px;
  height: 24px;
}

/* 添加处方卡片样式 */
.prescription-card {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 15px;
  margin: 10px 0;
  white-space: pre-line;
  transition: background-color 0.3s;
}

.prescription-card:hover {
  background-color: #e9ecef;
}

.prescription-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item .label {
  font-weight: bold;
  color: #4a90e2;
  margin-right: 10px;
}

.drug-list {
  margin-top: 8px;
}

.drug-item {
  padding: 8px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 8px;
}

/* 添加新的样式到 <style scoped> 部分的末尾 */
.el-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.el-dialog__body {
  padding: 24px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  color: #333;
  font-weight: 500;
}

.el-input {
  width: calc(100% - 120px);  /* 给按钮留出空间 */
}

.el-button {
  margin-left: 8px;
  border-radius: 4px;
}

.el-button--primary {
  background-color: #1677ff;
  border-color: #1677ff;
}

.el-button--primary:hover {
  background-color: #4096ff;
  border-color: #4096ff;
}

/* 发送处方按钮样式 */
.el-dialog__footer .el-button {
  padding: 8px 24px;
  font-size: 14px;
}

/* 只针对新建处方对话框的输入框组 */
.el-dialog .el-form-item {
  display: flex;
  align-items: center;
}

.el-dialog .el-form-item__content {
  display: flex;
  align-items: center;
  flex: 1;
}

/* 添加新的样式规则 */
.el-form-item.hidden-label {
  display: none !important;  /* 完全隐藏包含 ID 的表单项 */
}

/* 修改表单项的样式 */
.el-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.el-form-item {
  margin-bottom: 24px;
  border-radius: 4px;
  background: #fff;
}

.el-form-item__label {
  font-size: 14px;
  color: #333;
  font-weight: normal;
}

.el-form-item__content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-input {
  flex: 1;
}

/* 列表按钮样式 */
.el-form-item__content .el-button {
  min-width: 100px;
  margin-left: 8px;
}
</style>
